# author:Zhu yiwen
# date:20180108 10:29 +0800
# E-mail:zhuyiwen55@126.com
# description: use the newtown iteration method to solve the root of equation.

# define the f(x)
def NewFx(x, a, b, c):
    fx = a * x ** 2.0 + b * x + c
    return fx

# define the first order of the f(x)
def NewDFx(x, a, b):
    dfx = 2.0 * a * x + b
    return dfx

# the calculation formula of the newtown's iteration
def get_root(x0, max_iter, tol):
    p0 = x0 * 1.0
    for i in range(max_iter):
        p = p0 - NewFx(p0, a1, b1, c1) / NewDFx(p0, a1, b1)
        if abs(p - p0) < tol:
            return 'after the %sth iteration,the estimated value is %s.the root of f(x) are x1= %s and x2= %s' % (
            i, p, p, -b1 / a1 - p)
        p0 = p

# the two term coefficient could not equal zero
def Error1():
    print("error1：a should>0")
    print("")

# only when the b**2.0-4*a*c >0, the equation have the root
def Error2():
    print("error2：delta should >0")
    print("")

# assign the value for a, b, c, the initial value , the maximum number of iterations and the error limit
while True:
    a1 = float(input("please input a: （it could not equal 0）："))
    b1 = float(input("please input b："))
    c1 = float(input("please input c："))
    x0 = float(input("please input the initial value："))
    max_iter=float(input("please input the maximum number of iterations："))
    tol=float(input("please input the error limit："))
# if the equation have the root, calculate the solution
    if a1 != 0 and (b1 * b1 - 4 * a1 * c1) >= 0:
        print(get_root(x0, max_iter, tol))
        print("Done")
# if the equation do not have the root, tell the user
    else:
        if a1 == 0:
            Error1()
        if (b1 * b1 - 4 * a1 * c1) < 0:
            Error2()